module Main where

import Prelude hiding (readFile, writeFile, log, putStrLn, getLine)
import Data.Maybe ( fromMaybe )
import System.Environment (getArgs)
import System.Console.GetOpt
import System.Exit (ExitCode(..), exitWith)
import System.IO.UTF8 (readFile, writeFile, putStrLn, getLine, hPutStr)
import System.IO hiding (readFile, writeFile, putStrLn, getLine, hPutStr)

data Flag = Version | Help | Config String
       deriving (Show, Eq)

options :: [OptDescr Flag]
options =
 [ Option ['V'] ["version"]    (NoArg Version)            ""
 , Option ['h'] ["help"]       (NoArg Help)                "help"
 , Option ['c'] ["config"]     (ReqArg ConfigFileName "fname")  "config file name"
 ]
optionsUsage = "Usage: Hixay [OPTION...] command"

main :: IO ()
main = do
    argv <- getArgs
    case parse argv of
        ([], [], []) -> help
        (opts, [], errs)
            | Help `elem` opts -> help
            | Version `elem` opts -> version
            | otherwise -> die "source filename is required"
        (opts, (filename:[]), _)
            | Help `elem` opts -> help
            | Version `elem` opts -> version
            | (SrcKsss `elem` opts) && not (null $ ofn opts) ->
                    readFile filename >>= writeFile (ofn opts). ppTopElement .
                            makeSender (ns opts) (ent opts) . map (\w -> makeElemFromDDL (SqlField w "" True)) . words . head . lines
            | (MappingCSV `elem` opts) -> produceMappingFile filename opts
            | (Receiver `elem` opts) || (Sender `elem` opts) -> proceedTxtFile filename opts
            | otherwise -> die "Error: sender/receiver mode unspecified"
    where
        parse a = getOpt Permute options a
        info = usageInfo optionsUsage options
        dump = hPutStrLn stderr
        -- die errs = dump (concat errs ++ info) >> exitWith (ExitFailure 1)
        die errtxt = dump errtxt >> exitWith (ExitFailure 1)
        help = dump info >> exitWith ExitSuccess
        version = dump "version here" >> exitWith ExitSuccess
        --
        ofn opts = concat $ take 1 [fn | OutputFileName fn <- opts]
        ns opts = concat $ take 1 [fn | NameSpace fn <- opts]
        ent opts = concat $ take 1 [fn | Entity fn <- opts]



